package com.xuhf.boot;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/message")
public class SendMessageController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/send")
    public String sendMesasge() {
        DefaultMQProducer producer = rocketMQTemplate.getProducer();
        Map<String, Object> map = new HashMap<>();
        map.put("username", "xuhf");
        map.put("age", "27");

        Map<String, Object> header = new HashMap<>();
        header.put("headerName", "xuhf");
        header.put("headerAge", "27");
        String topic = "01-boot-hello";
        rocketMQTemplate.convertAndSend("01-boot-hello:tagB", JSONObject.toJSONString(map), header);
        rocketMQTemplate.syncSend(topic, JSONObject.toJSONString(map));
        rocketMQTemplate.asyncSend(topic, JSONObject.toJSONString(map), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("消息发送成功");
            }

            @Override
            public void onException(Throwable e) {
                System.err.println("消息发送失败");
            }
        });
        rocketMQTemplate.sendOneWay(topic,JSONObject.toJSONString(map));
        rocketMQTemplate.syncSend("01-boot-hello", MessageBuilder.withPayload(JSONObject.toJSONString(map)).build(), 3000, 3);
        Message<?> msg = MessageBuilder.withPayload(JSONObject.toJSONString(map)).setHeader(MessageConst.PROPERTY_KEYS, "1100").build();
        rocketMQTemplate.send("01-boot-hello", msg);
        return "success";
    }

}
